const app = getApp();

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function wxPromisify(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res)
      }

      obj.fail = function (res) {
        reject(res)
      }

      fn(obj)
    })
  }
}


//授权验证(登陆规范修改后的)
function isAccredit(cb) {
  let isAccredit = false;
  var app = getApp();
  console.log(app.globalData.userInfo);
  if (app.globalData.userInfo.Avatar.indexOf('userdefault.png') == -1) {
    isAccredit = true;
  }
  cb(isAccredit);
  // 查看是否授权
  // wx.getSetting({
  //   success: function (res) {
  //     if (res.authSetting['scope.userInfo']) {// 已授权
  //       isAccredit = true;
  //     }
  //     cb(isAccredit);
  //   }
  // })
}

/**
 * 会员的操作记录
 * 参数actionType:2 转发名片, 3 复制微信, 7 保存电话, 9 拨打电话
 */
function aiCardActionRecord(actionType) {
  var app = getApp();
  var cardId = wx.getStorageSync("cardId")
  if (cardId) {
    wx.request({
      url: app.globalData.host + '/api/BusinessCard/AddAiCardAction?staffId=' + cardId + '&uid=' + app.globalData.userInfo.Uid + '&actionType=' + actionType + '&storeId=' + app.globalData.storeId,
      success: function (res) {
        if (res.data.Code == 0) {

        }
      },
    })
  }

}


//判断两个时间比较大小
function compareDate(d1, d2) {
  return ((new Date(d1.replace(/-/g, "\/"))) > (new Date(d2.replace(/-/g, "\/"))));
}

//当前时间获取
function getCurrentToday() {
  const date = new Date()
  var year = date.getFullYear();
  var mouths = (date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : (date.getMonth() + 1);
  var day = date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate();
  var hours = date.getHours() < 10 ? ("0" + date.getHours()) : date.getHours();
  var Minutes = date.getMinutes() < 10 ? ("0" + date.getMinutes()) : date.getMinutes(); //当前分
  var ss = date.getSeconds() < 10 ? ("0" + date.getSeconds()) : date.getSeconds();
  var currentdate = year + "-" + mouths + "-" + day + "\t" + hours + ":" + Minutes + ":" + ss;
  return currentdate;
}

// 当前时间加一天得到新日期
function jiaDate(dataStr, dayCount) {
  var strdate = dataStr; //日期字符串
  var isdate = new Date(strdate.replace(/-/g, "/")); //把日期字符串转换成日期格式
  isdate = new Date((isdate / 1000 + (86400 * dayCount)) * 1000); //日期加1天
  // var pdate = isdate.getFullYear() + "-" + (isdate.getMonth() + 1) + "-" + (isdate.getDate());
  return isdate;
}
// 当前时间减一天得到新日期
function jianDate(dataStr, dayCount) {
  var strdate = dataStr; //日期字符串
  var isdate = new Date(strdate.replace(/-/g, "/")); //把日期字符串转换成日期格式
  isdate = new Date((isdate / 1000 - (86400 * dayCount)) * 1000); //日期减1天
  // var pdate = isdate.getFullYear() + "-" + (isdate.getMonth() + 1) + "-" + (isdate.getDate());
  return isdate;
}

//获取手机号
function getMobile(e, callback) {
  var app = getApp();
  var that = this;
  wx.login({
    success: function (res) {
      var code = res.code;
      wx.request({
        url: app.globalData.host + '/api/account/getphonenumber?encryptedData=' + encodeURIComponent(e.detail.encryptedData) + '&iv=' + encodeURIComponent(e.detail.iv) + '&storeid=' + app.globalData.storeId + '&storeAppId=' + app.globalData.storeAppId + "&code=" + code,
        success: function (res) {
          if (res.data.Code == 0) {
            app.globalData.userInfo.Mobile = res.data.Data;
            wx.setStorageSync("mobile", res.data.Data);
            if (callback) {
              callback(res.data.Data)
            }
          }
        },
      })
    }
  })
}

//图片路径拼接
function formatAvater(avater, imgPath) {
  if (avater != null && avater.indexOf("http") == 0) {
    return avater;
  } else {
    return imgPath + avater;
  }
}
//图片路径拼接(商品头图)
function formatAvaterByProHead(avater) {
  const app = getApp();
  if (avater != null && avater.indexOf("http") == 0) {
    return avater;
  } else {
    return 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/show/source/' + avater;
  }
}

function getCardId(userid, callback) {
  var that = this;
  wx.showLoading({
    title: '加载中',
    mask: true,
  })
  wx.request({
    url: app.globalData.host + '/api/Staff/GetStaffIdByUid?Uid=' + userid,
    success: function (res) {
      wx.hideLoading();
      if (res.data.Code == 0) {
        if (res.data.Data) {
          callback(res.data.Data.Id)
        } else {
          wx.showModal({
            title: '提示',
            content: "该成员还未创建玖玖客！",
            showCancel: false
          })
          return
        }
      }
    },
  })
}

//当前定位
function getLocation(callback){
  let location = wx.getStorageSync("location");
  if(!location){
    location = {lat: 0,lng: 0};
  }
  if(location.lat > 0 && location.lng > 0){
    callback(location);
    return;
  }  

  wx.getLocation({
    type: 'gcj02',
    success(res) {
      console.log('获取定位',res);  
      if (res.latitude != null && res.latitude != undefined) {
        location.lat = res.latitude;
      }
      if (res.longitude != null && res.longitude != undefined) {
        location.lng = res.longitude;
      } 
      wx.setStorageSync('location', location);
      callback(location);
    },
    fail(res) {
      console.log('获取定位失败',res)
      wx.setStorageSync('location', location);
      callback(location);
    }
  })
}

//获取url参数值: name：参数名
function getQuery(url, name) {
  url = url.indexOf('?')>-1 ? url.substr(url.indexOf('?')+1) : url;
  var arr = url.split('&');
  for(var i = 0; i < arr.length; i++) {
      var ar = arr[i].split('=');
      if (ar[0] == name) {
          if (unescape(ar[1]) == 'undefined') {
            return '';
          } else {
            return unescape(ar[1]);
          }
      }
  }
  return '';
}

function showModal(content){
  wx.showModal({
    title: '提示',
    content: content,
    showCancel: false
  })    
}

function showToast(title,icon = 'none'){
  wx.showToast({
    title: title,
    icon: icon
  })
}
module.exports = {
  wxPromisify: wxPromisify,
  formatTime: formatTime,
  aiCardActionRecord: aiCardActionRecord,
  getCurrentToday: getCurrentToday,
  compareDate: compareDate,
  getMobile: getMobile,
  formatAvater: formatAvater,
  formatAvaterByProHead: formatAvaterByProHead,
  jiaDate: jiaDate,
  jianDate: jianDate,
  isAccredit: isAccredit,
  getCardId: getCardId,
  getLocation: getLocation,
  showModal: showModal,
  showToast: showToast,
  getQuery: getQuery
}